#!/usr/bin/perl

my $hosts = ['127.0.0.1','ldap.qmail.info'];

######################################################################
# uncoment in case you want to see all the ENV vars
#open (MYFILE, '>>/tmp/data.txt');
#  print MYFILE "$limit";
#foreach $key (sort(keys %ENV)) {
#  print MYFILE "$key = $ENV{$key}\n";
#}
#close(MYFILE);

my $from = lc($ENV{SMTPAUTHUSER});

if(!$from) {
 exit 0;
}

$db_file ='/var/qmail/control/smtpThrottle.db';

use DB_File;
tie (%db, 'DB_File', "$db_file", O_CREAT|O_RDWR, 0664, $DB_HASH) || die ("Can't open DB File, $!\n");

use Net::LDAP;
$ldap = Net::LDAP->new($hosts, timeout=>7); 
if ($ldap) {
  $mesg = $ldap->bind;
  $mesg = $ldap->search(base => 'ou=vusers,dc=qmail,dc=info',filter => "(&(objectclass=qmailuser)(uid=$from))",attrs => ['smtpThrottle']);
  my @entries = $mesg->entries;
  if(@entries) {
    $limit=$entries[0]->get_value('smtpThrottle');
  } else {
    $limit = 10;
  }
} else {
  $limit = 10;
}

$today = (localtime(time))[3];

if ($limit eq '') {
  $limit = 10;
}

if($limit == 0) {
  if ($db{$from}) {
    ($day,$msgs) = split(/:/, $db{$from});
    $msgs = $msgs + 1;
    $db{$from} = join(":", $today, $msgs, $limit);
    untie (%db);
    exit 0;
  }
}

if ($db{$from}) {
  ($day,$msgs) = split(/:/, $db{$from});
  if ($msgs <= $limit && $day == $today) {
    $msgs = $msgs + 1;
    $db{$from} = join(":", $day, $msgs, $limit);
    untie (%db);
    exit 0;
  } elsif ($day != $today) {
    $db{$from} = join(":", $today, 2, $limit);
    untie (%db);
    exit 0;
  } else {
    print STDERR "Outgoing mail quota exceeded\n"; exit (31);
  }
} else {
  $db{$from} = join(":", $today, 2, $limit);
}

untie (%db);